Android Programming File Reading and Writing Operations and Skills Summary [Classic Collection]

  • 2021-07-26 08:53:34
  • OfStack

This paper summarizes the reading and writing operations of Android files with examples. Share it for your reference, as follows:

Files in Android are placed in different locations, and their reading methods are also different.
In this paper, the ways and methods of reading resource files, data area files, SD card files and RandomAccessFile in android are sorted out. For reference.

1. Reading resource files:

1) Read file data from raw of resource:


String res = "";
try{
  // Object in the resource Raw Data stream 
  InputStream in = getResources().openRawResource(R.raw.test);
  // Get the size of the data 
  int length = in.available();
  byte [] buffer = new byte[length];
  // Read data 
  in.read(buffer);
  // Yi test.txt Choose the appropriate encoding type of, if not adjusted, it will be garbled 
  res = EncodingUtils.getString(buffer, "BIG5");
  // Shut down 
  in.close();
}catch(Exception e){
  e.printStackTrace();
}

2) Read file data from asset of resource


String fileName = "test.txt"; // File name 
String res="";
try{
  // Object in the resource asset Data stream 
  InputStream in = getResources().getAssets().open(fileName);
  int length = in.available();
  byte [] buffer = new byte[length];
  in.read(buffer);
  in.close();
  res = EncodingUtils.getString(buffer, "UTF-8");
}catch(Exception e){
  e.printStackTrace();
}

2. Readwrite/data/data/ < Application name > Files on the directory:


// Write data 
public void writeFile(String fileName,String writestr) throws IOException{
 try{
    FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);
    byte [] bytes = writestr.getBytes();
    fout.write(bytes);
    fout.close();
   }
    catch(Exception e){
    e.printStackTrace();
    }
}
// Read data 
public String readFile(String fileName) throws IOException{
 String res="";
 try{
     FileInputStream fin = openFileInput(fileName);
     int length = fin.available();
     byte [] buffer = new byte[length];
     fin.read(buffer);
     res = EncodingUtils.getString(buffer, "UTF-8");
     fin.close();
   }
   catch(Exception e){
     e.printStackTrace();
   }
   return res;
}

3. Read and write files in SD card. That is, the file under the/mnt/sdcard/ directory:


// Write data to SD Files in 
public void writeFileSdcardFile(String fileName,String write_str) throws IOException{
 try{
    FileOutputStream fout = new FileOutputStream(fileName);
    byte [] bytes = write_str.getBytes();
    fout.write(bytes);
    fout.close();
   }
   catch(Exception e){
    e.printStackTrace();
    }
  }
// Read SD Files in 
public String readFileSdcardFile(String fileName) throws IOException{
 String res="";
 try{
     FileInputStream fin = new FileInputStream(fileName);
     int length = fin.available();
     byte [] buffer = new byte[length];
     fin.read(buffer);
     res = EncodingUtils.getString(buffer, "UTF-8");
     fin.close();
    }
    catch(Exception e){
     e.printStackTrace();
    }
    return res;
}

4. Read and write files using the File class:


// Read a file 
public String readSDFile(String fileName) throws IOException {
    File file = new File(fileName);
    FileInputStream fis = new FileInputStream(file);
    int length = fis.available();
     byte [] buffer = new byte[length];
     fis.read(buffer);
     res = EncodingUtils.getString(buffer, "UTF-8");
     fis.close();
     return res;
}
// Write a file 
public void writeSDFile(String fileName, String write_str) throws IOException{
    File file = new File(fileName);
    FileOutputStream fos = new FileOutputStream(file);
    byte [] bytes = write_str.getBytes();
    fos.write(bytes);
    fos.close();
}

5. In addition, the File class has the following one common operation:


String Name = File.getName(); // Get the name of the file or folder: 
String parentPath = File.getParent(); // Get the parent directory of a file or folder 
String path = File.getAbsoultePath();// Absolute path 
String path = File.getPath();// Relative path 
File.createNewFile();// Create a file 
File.mkDir(); // Create a folder 
File.isDirectory(); // Determine whether it is a file or folder 
File[] files = File.listFiles(); // List all files and folder names under folders 
File.renameTo(dest); // Modify folder and file names 
File.delete(); // Delete a folder or file 

6. Read and write files using RandomAccessFile:

RandomAccessFile is flexible and has many functions. You can jump to any position of the file in a way similar to seek, and start reading and writing from the current position of the file indicator.

There are two ways to construct it


new RandomAccessFile(f,"rw");// Read and write mode 
new RandomAccessFile(f,"r");// Read-only mode 

Use case:


/*
 *  Program function: Demonstrates the RandomAccessFile Class, while implementing the operation of the 1 File copy operations. 
 */
import java.io.*;
public class RandomAccessFileDemo {
 public static void main(String[] args) throws Exception {
 RandomAccessFile file = new RandomAccessFile("file", "rw");
 //  Below file Write data in file 
 file.writeInt(20);//  Account for 4 Bytes 
 file.writeDouble(8.236598);//  Account for 8 Bytes 
 file.writeUTF(" This is 1 A UTF String ");//  This length is written at the first two bytes of the current file pointer and is available readShort() Read 
 file.writeBoolean(true);//  Account for 1 Bytes 
 file.writeShort(395);//  Account for 2 Bytes 
 file.writeLong(2325451l);//  Account for 8 Bytes 
 file.writeUTF(" Again 1 A UTF String ");
 file.writeFloat(35.5f);//  Account for 4 Bytes 
 file.writeChar('a');//  Account for 2 Bytes 
 file.seek(0);//  Set the file pointer position to the beginning of the file 
 //  Below from file When reading data in a file, pay attention to the position of the file pointer 
 System.out.println(" From file Read data at the specified location of the file--- ");
 System.out.println(file.readInt());
 System.out.println(file.readDouble());
 System.out.println(file.readUTF());
 file.skipBytes(3);//  Skip the file pointer 3 Bytes, which is skipped in this example 1 A boolean Value sum short Value. 
 System.out.println(file.readLong());
 file.skipBytes(file.readShort()); //  Skip "Again" in the file 1 A UTF Bytes occupied by string, note readShort() Method moves the file pointer, so you don't need to add the 2 . 
 System.out.println(file.readFloat());
 // The following demonstrates file copy operations 
 System.out.println(" File copy (from file To fileCopy )----- ");
 file.seek(0);
 RandomAccessFile fileCopy=new RandomAccessFile("fileCopy","rw");
 int len=(int)file.length();// Gets the length of the file (in bytes) 
 byte[] b=new byte[len];
 file.readFully(b);
 fileCopy.write(b);
 System.out.println(" Copy complete! ");
 }
}

7. When reading a resource file, can you jump to any location of the file and read the specified number of bytes from the specified location in a way similar to seek?
The answer is yes.

The following functions are available in both FileInputStream and InputStream:


public long skip (long byteCount); // Skip from the data flow n Bytes 
public int read (byte[] buffer, int offset, int length); // Read from the data stream length Data presence buffer Adj. offset The starting position. offset Is relative to buffer Is not the data stream. 

You can use these two functions to implement operations similar to seek, as shown in the following test code:


// Among them read_raw Yes 1 A txt Documents, stored in raw Directory. 
//read_raw.txt The contents of the document are: "ABCDEFGHIJKLMNOPQRST"
public String getRawString() throws IOException {
  String str = null;
  InputStream in = getResources().openRawResource(R.raw.read_raw);
  int length = in.available();
  byte[] buffer = new byte[length];
  in.skip(2); // Skip two bytes 
  in.read(buffer,0,3); // Read 3 Bytes 
  in.skip(3); // Skip 3 Bytes 
  in.read(buffer,0,3); // Read 3 Bytes 
  // Finally str="IJK"
  str = EncodingUtils.getString(buffer, "BIG5");
  in.close();
  return str;
}

As can be seen from the above example, the skip function is somewhat similar to the seek operation in the C language, but there are some differences between them.

It should be noted that:

1. The skip function always jumps from the current position. In practical application, we should judge the return value of this function under 1.

2. The read function is always read from the current position.

3. Alternatively, you can use the reset function to reset the current position of the file to 0, which is the starting position of the file.

How do I get the current location of the file?

I did not find the relevant functions and methods, do not know how to get the current location of the file, it seems that it is not too important.

8. How do I get InputStream from FileInputStream?


String fileName = "test.txt"; // File name 
String res="";
try{
  // Object in the resource asset Data stream 
  InputStream in = getResources().getAssets().open(fileName);
  int length = in.available();
  byte [] buffer = new byte[length];
  in.read(buffer);
  in.close();
  res = EncodingUtils.getString(buffer, "UTF-8");
}catch(Exception e){
  e.printStackTrace();
}

0

9. The size of an APK resource file cannot exceed 1M. What if it exceeds 1M? We can copy this data to the data directory and then use it again. The code for copying data is as follows:


String fileName = "test.txt"; // File name 
String res="";
try{
  // Object in the resource asset Data stream 
  InputStream in = getResources().getAssets().open(fileName);
  int length = in.available();
  byte [] buffer = new byte[length];
  in.read(buffer);
  in.close();
  res = EncodingUtils.getString(buffer, "UTF-8");
}catch(Exception e){
  e.printStackTrace();
}

1

Summary:

1. There are two kinds of resource files in apk, which are opened in two different ways.

raw uses:


String fileName = "test.txt"; // File name 
String res="";
try{
  // Object in the resource asset Data stream 
  InputStream in = getResources().getAssets().open(fileName);
  int length = in.available();
  byte [] buffer = new byte[length];
  in.read(buffer);
  in.close();
  res = EncodingUtils.getString(buffer, "UTF-8");
}catch(Exception e){
  e.printStackTrace();
}

2

asset uses:


InputStream in = getResources().getAssets().open(fileName);

This data can only be read, not written. More importantly, the file size in this directory cannot exceed 1M.

Also, it should be noted that when using InputStream, you need to add throws IOException after the function name.

2. The files in SD card are operated by FileInputStream and FileOutputStream.

3. Files stored in the data area (/data/data/...) can only be operated with openFileOutput and openFileInput.

Note that FileInputStream and FileOutputStream cannot be used for file operation.

4. The RandomAccessFile class is limited to file operations and cannot access other IO devices. It can jump to any location in the file and start reading and writing from the current location.

5. Both InputStream and FileInputStream can use skip and read (buffre, offset, length) functions to realize random reading of files.

For more readers interested in Android related contents, please check the topics on this site: "Summary of Android File Operation Skills", "Summary of SD Card Operation Methods for Android Programming Development", "Introduction and Advanced Tutorial for Android Development", "Summary of Android Resource Operation Skills", "Summary of View Skills for Android View" and "Summary of Android Control Usage"

I hope this article is helpful to everyone's Android programming.


Related articles: